#!/bin/bash
# 公共机器人
# 监控处理器、内存、磁盘、网络上下 2022年11月8日
# 定时任务
# ① 01 12 * * * /bin/bash /sh/dingding.sh 1 > /sh/log
# ② */1 * * * * /bin/bash /sh/dingding.sh 2 >> /sh/log
# 初始化
# ③ mkdir /sh/ || touch /sh/.RAM /sh/.CPU /sh/.DISK /sh/.UPLOAD /sh/.DOWNLOAD && echo 0 > /sh/.RAM && echo 0 > /sh/.CPU && echo 0 > /sh/.DISK && echo 0 > /sh/.UPLOAD && echo 0 > /sh/.DOWNLOAD && yum -y install iftop

#全局
ip="测试机"
# 测试消息API
dingding="cb325fec346688244334aa53e3c11046fdb6abd9e9d0712c08bf4508c811d92a"
# 群API
#dingding="e8f778cfc74c7f822bd237959b8851b26c638fa9d3d5f76aed9cbdd79340953a"
msg_date=""
msg_mem=""
msg_cpu=""
msg_disk=""
netsend=""
netreceive=""

#判断大小
function bashi() {
	op=$(echo $1 | awk -F "." '{print $1}')
	if [[ $op -gt 80 ]] && [[ `cat /sh/.$2` == 0 ]]; then
		curl "https://oapi.dingtalk.com/robot/send?access_token=$dingding" -H 'Content-Type: application/json' -d '{"msgtype": "text","text": {"content": "'"巡检告警（$ip） \n $2已使用超过80% 当前为：$1% "'"},"at":{"atMobiles": [ "项目巡检" ],"isAtAll": false}}'
		echo 1 > /sh/.$2
	elif [[ $op -lt 80 ]] && [[ `cat /sh/.$2` == 1 ]]; then
		curl "https://oapi.dingtalk.com/robot/send?access_token=$dingding" -H 'Content-Type: application/json' -d '{"msgtype": "text","text": {"content": "'"巡检告警恢复（$ip） \n $2已使用超过80% 当前为：$1% 告警取消 "'"},"at":{"atMobiles": [ "项目巡检" ],"isAtAll": false}}'
		echo 0 > /sh/.$2
    fi
}

#判断大小
function netbashi() {
# netbashi 40Mb "上行"
	mb="Mb"
	kb="Kb"
	b="b"
	new=$(echo $1 | sed 's/Mb//g' | sed 's/Kb//g' | sed 's/b//g' | awk -F "." '{print $1}')
	if [[ $1 =~ $mb ]] && [[ $new -gt $3 ]] && [[ `cat /sh/.$2` == 0 ]]; then
		curl "https://oapi.dingtalk.com/robot/send?access_token=$dingding" -H 'Content-Type: application/json' -d '{"msgtype": "text","text": {"content": "'"巡检告警（$ip） \n $2带宽已使用超过80% 当前为：$1 每秒"'"},"at":{"atMobiles": [ "项目巡检" ],"isAtAll": false}}'
        echo 1 > /sh/.$2
    elif [[ $1 =~ $kb || $1 =~ $b ]] || [[ $1 =~ $mb ]] && [[ $new -lt $3 ]] && [[ `cat /sh/.$2` == 1 ]]; then
        curl "https://oapi.dingtalk.com/robot/send?access_token=$dingding" -H 'Content-Type: application/json' -d '{"msgtype": "text","text": {"content": "'"巡检告警恢复（$ip） \n $2带宽已使用超过80% 当前为：$1 每秒 告警取消 "'"},"at":{"atMobiles": [ "项目巡检" ],"isAtAll": false}}'
        echo 0 > /sh/.$2
	fi
}

#获取此时的内存、磁盘、网络和处理器占用率（%）
function getValue() {
    #时间
    date=$(date +"%m-%d %H:%M")

    #内存
    memuse=$(free -m | sed -n '2p' | awk '{print $3}')
    memall=$(free -m | sed -n '2p' | awk '{print $2}')
    freerate=$(echo $memuse $memall |awk '{printf ("%.2f\n",($1/$2)*100)}')

    #处理器
    cpuuse=`echo $(vmstat -w 2 2 | sed -n '4p' | awk -F ' ' '{print $13,$14}') | awk '{print $1+$2}'`

    #磁盘
    diskuse=$(df -hT | grep -w "/" | awk '{print $6}' | sed 's/%//g')

    #带宽
    netall=$(/usr/sbin/iftop -t -s 3 | grep Total | awk '{print $(NF-2)}')
    netsend=$(echo $netall | awk '{print $1}')
    netreceive=$(echo $netall | awk '{print $2}')
    netSaR=$(echo $netall | awk '{print $3}')
	
	#echo "时间"$date",内存："$freerate",处理器："$cpuuse",磁盘："$diskuse",网络(每秒)："$netsend（发送）,$netreceive（接收）,$netSaR（总共）
	echo $date","$freerate","$cpuuse","$diskuse","$netsend","$netreceive >> /sh/.tmp

    # msg_date=$(echo "时间："$date)
    # msg_mem=$(echo "内存："$freerate"%")
    # msg_cpu=$(echo "处理器："$cpuuse"%")
    # msg_disk=$(echo "磁盘："$diskuse"%")
    # msg_net=$(echo "网络(秒)："$netsend"(发)",$netreceive"(收)",$netSaR"(共)")
}

# main 定时巡检
if [[ $1 -eq 1 ]]; then
  #getValue
  memMax=$(cat /sh/.tmp | awk -F "," '{print $2}' | awk 'BEGIN{ max = 0} {if ($1 > max) max = $1; fi} END{printf "%.2f\n",max}')
  cpuMax=$(cat /sh/.tmp | awk -F "," '{print $3}' | awk 'BEGIN{ max = 0} {if ($1 > max) max = $1; fi} END{printf "%.2f\n",max}')
  # 区分Mb
  cat /sh/.tmp | awk -F "," '{print $5}' | grep Mb > /dev/null 2>&1
  if [[ $? -eq 0 ]];then
	sendMax=$(cat /sh/.tmp | awk -F "," '{print $5}' | grep "Mb" | sed 's/Mb//g'| awk 'BEGIN{ max = 0} {if ($1 > max) max = $1; fi} END{printf "%.2f\n",max}' | sed 's/$/Mb\/s/g')
  else
	sendMax=$(cat /sh/.tmp | awk -F "," '{print $5}' | grep "Kb" | sed 's/Kb//g' | awk 'BEGIN{ max = 0} {if ($1 > max) max = $1; fi} END{printf "%.2f\n",max}' | sed 's/$/Kb\/s/g')
  fi
  # 区分Kb
  cat /sh/.tmp | awk -F "," '{print $6}' | grep Mb > /dev/null 2>&1
  if [[ $? -eq 0 ]];then
	receiveMax=$(cat /sh/.tmp | awk -F "," '{print $6}' | grep "Mb" | sed 's/Mb//g' | awk 'BEGIN{ max = 0} {if ($1 > max) max = $1; fi} END{printf "%.2f\n",max}' | sed 's/$/Mb\/s/g')
  else
	receiveMax=$(cat /sh/.tmp | awk -F "," '{print $6}' | grep "Kb" | sed 's/Kb//g' | awk 'BEGIN{ max = 0} {if ($1 > max) max = $1; fi} END{printf "%.2f\n",max}' | sed 's/$/Kb\/s/g')
  fi

  curl "https://oapi.dingtalk.com/robot/send?access_token=$dingding" -H 'Content-Type: application/json' -d '{"msgtype": "text","text": {"content": "'"定时巡检（$ip） \n 今天0点截至 `date +"%m-%d %H:%M"` \n 峰值数据 \n 内存：$memMax% \n 处理器： $cpuMax% \n 上行带宽：$sendMax \n 下行带宽：$receiveMax "'"},"at":{"atMobiles": [ "项目巡检" ],"isAtAll": false}}'
else
  #获取
  getValue
  #判断
  bashi $freerate RAM
  bashi $cpuuse CPU
  bashi $diskuse DISK
  netbashi $netsend UPLOAD 180
  netbashi $netreceive DOWNLOAD 280
fi
